<?php
namespace app\system\controller;

use org\util\FileUtil;

class CodeController extends BaseController
{

    /**
     * 初始化
     */
    protected function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $path = $this->request->param('path' );
        if(empty($path)){
            $path = 'tpl';
        }
        $list = FileUtil::Tree($path);
        $this->assign('path',$path);
        $this->assign('siteId',$this->getSiteId());
        $this->assign('list', $list);
        return $this->fetch();
    }

    /**
     * 修改文件
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            $code     = htmlspecialchars_decode($_POST['code']);
            $filename = $_POST['filename'];
            file_put_contents($filename, $code);
            $this->success('保存成功！');
        }
        $filename = $this->request->param('filename');
        $code     = file_get_contents($filename);
        $this->assign('filename', $filename);
        $this->assign('code', htmlspecialchars($code));
        return $this->fetch();
    }

    /**
     * 创建文件
     */
    public function createFile()
    {
        $type = $this->request->param('type');
        $filename = $this->request->param('filename');
        if ($type == 'file') {
            if (FileUtil::createFile($filename)) {
                $this->success('创建成功！');
            } else {
                $this->error('创建失败，请检查目录权限！');
            }
        } else {
            if (FileUtil::createDir($filename)) {
                $this->success('创建成功！');
            } else {
                $this->error('创建失败，请检查目录权限！');
            }
        }
    }

    /**
     * 删除文件
     */
    public function delFile()
    {
        $file = $this->request->param('file');
        $type = $this->request->param('type');
        if ($type == 'file') {
            if (FileUtil::unlinkFile($file)) {
                $this->success('删除成功！');
            } else {
                $this->error('删除失败，请检查目录权限！');
            }
        } else {
            if (FileUtil::unlinkDir($file)) {
                $this->success('删除成功！');
            } else {
                $this->error('删除失败，请检查目录权限！');
            }
        }
    }

}
